package io.github.lee.app.unsplash.global.di.http

import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

private const val TIMEOUT = 10L
private val timeUnit = TimeUnit.SECONDS

@Module
@InstallIn(SingletonComponent::class)
object HttpModule {
    private var baseUrl = ""
    private val interceptorList = mutableListOf<Interceptor>()

    fun init(baseUrl: String, interceptorList: List<Interceptor>) {
        HttpModule.baseUrl = baseUrl
        HttpModule.interceptorList.clear()
        HttpModule.interceptorList.addAll(interceptorList)
    }

    @Provides
    fun provideOkHttp(): OkHttpClient {

        val builder = OkHttpClient.Builder()
            .connectTimeout(TIMEOUT, timeUnit)
//            .callTimeout(TIMEOUT, timeUnit)
            .readTimeout(TIMEOUT, timeUnit)
            .writeTimeout(TIMEOUT, timeUnit)
        if (interceptorList.isNotEmpty()) {
            interceptorList.forEach {
                builder.addInterceptor(it)
            }
        }
        return builder.build()
    }


    @Provides
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}